//
//  CZNetWork.m
//  JiaZhaengHuiYuan
//
//  Created by YYKJ1 on 2018/11/23.
//  Copyright © 2018年 YYKJ1. All rights reserved.
//

#import "CZNetWork.h"
#import "CZNetWorkManager.h"

@implementation CZNetWork
+(void)post:(NSString *)url params:(id)params success:(CZResponseSuccessBlock)success failure:(CZResponseFailureBlock)failure{
    CZNetWorkManager *manager = [CZNetWorkManager sharedInstance];
    
    
    //    [manager.requestSerializer setValue:@"application/x-www.form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    //    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //    [manager.requestSerializer setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
    
    [manager.requestSerializer setValue:@"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    NSLog(@"打印Post请求指针%@",manager.requestSerializer);
    
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary*result=[NSJSONSerialization JSONObjectWithData:responseObject options:0 error:NULL];
        if (success) {
            success(result);
            
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        NSLog(@"这里打印错误信息%@",error); //这里打印错误信息
        
    }];
    
}

+(void)get:(NSString *)url params:(id)params success:(CZResponseSuccessBlock)success failure:(CZResponseFailureBlock)failure{
    //    CZNetWorkManager *manager = [CZNetWorkManager sharedInstance];
    CZNetWorkManager *manager = [CZNetWorkManager sharedInstance];
    
    
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"bfSKmBrPnSSF6hVNwpOmnvOs" forHTTPHeaderField:@"X-LC-Key"];
    [manager.requestSerializer setValue:@"Xb0JQwLNESctk6PXdrgxeGiv-MdYXbMMI" forHTTPHeaderField:@"X-LC-Id"];
    
    NSLog(@"打印Get请求指针%@",manager.requestSerializer);
    
    [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary*result=[NSJSONSerialization JSONObjectWithData:responseObject options:0 error:NULL];
        if (success) {
            success(result);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        //NSLog(@"这里打印错误信息%@+++",error);//这里打印错误信息
        if (task.error.code == NSURLErrorCancelled) {
            // 取消了请求
            NSLog(@"取消了请求");
        } else {
            NSLog(@"网络请求失败！");
            NSLog(@"%@",error);
            
            if (error.code == NSURLErrorTimedOut) {
                NSLog(@"网络请求超时！");
                
            }
        }
    }];
    
}

//上传图片
+(void)loginAndRegisterWith:(NSString *)urlStr parameters:(id)paramesters dicy:(NSDictionary *)dicy requestData:(NSData *)data withName:(NSString *)name withFileName:(NSString *)fileName success:(CZResponseSuccessBlock)success fail:(CZResponseFailureBlock)fail {
    
    CZNetWorkManager *manager = [CZNetWorkManager sharedInstance];
    
    
    [manager POST:urlStr parameters:paramesters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        
        //把image  转为data , POST上传只能传data
        
        // NSData *data = UIImagePNGRepresentation(Image);
        
        //上传的参数(上传图片，以文件流的格式)
        
        //[formData appendPartWithFormData:body name:name];
        NSData *userData = [NSJSONSerialization dataWithJSONObject:dicy options:kNilOptions error:nil];
        
        // NSLog(@"%@",dicy);
        [formData appendPartWithFormData:userData name:name];
        
        [formData appendPartWithFileData:data name:name fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        
        //[formData appendPartWithFileData:data name:name fileName:fileName mimeType:@"image/png"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary*result=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:NULL];
        if (success) {
            success(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (fail) {
            fail(error);
            NSLog(@"网络请求失败！");
            NSLog(@"%@",error);
            
            if (error.code == NSURLErrorTimedOut) {
                NSLog(@"网络请求超时！");
                
            }
        }
    }];
    
}

+(void)postImage:(NSString *)urlStr parameters:(id)paramesters requestData:(NSData *)data withName:(NSString *)name withFileName:(NSString *)fileName success:(CZResponseSuccessBlock)success fail:(CZResponseFailureBlock)fail{
    CZNetWorkManager *manager = [CZNetWorkManager sharedInstance];
    
    
    [manager POST:urlStr parameters:paramesters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        
        //把image  转为data , POST上传只能传data
        // NSData *data = UIImagePNGRepresentation(Image);
        //上传的参数(上传图片，以文件流的格式)
        
        //[formData appendPartWithFormData:body name:name];
        [formData appendPartWithFormData:data name:name];
        [formData appendPartWithFileData:data name:name fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary*result=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:NULL];
        if (success) {
            success(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (fail) {
            fail(error);
            NSLog(@"网络请求失败！");
            NSLog(@"%@",error);
            
            if (error.code == NSURLErrorTimedOut) {
                NSLog(@"网络请求超时！");
                
            }
        }
    }];
    
}
//+(void)getloginAndRegisterWith:(NSString *)urlStr parameters:(id)paramesters requestData:(NSData *)data withName:(NSString *)name withFileName:(NSString *)fileName success:(CZResponseSuccessBlock)success fail:(CZResponseFailureBlock)fail{
//
//    CZNetWorkManager *manager = [CZNetWorkManager sharedInstance];
//
//    //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
//
//    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//
//
//        //把image  转为data , POST上传只能传data
//
//        //NSData *data = UIImagePNGRepresentation(Image);
//
//        //上传的参数(上传图片，以文件流的格式)
//
//        //[formData appendPartWithFormData:body name:name];
//
//        [formData appendPartWithFileData:data name:name fileName:fileName mimeType:@"image/jpg/png/jpeg"];
//
//
//    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        if (success) {
//            success(responseObject);
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        if (fail) {
//            fail(error);
//        }
//    }];
//
//}

//FormData
+(void)loginAndRegisterWith:(NSString *)urlStr parameters:(id)paramesters  success:(CZResponseSuccessBlock)success fail:(CZResponseFailureBlock)fail {
    CZNetWorkManager *manager = [CZNetWorkManager sharedInstance];
    
    // [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //NSData *userData = [NSJSONSerialization dataWithJSONObject:paramesters options:kNilOptions error:nil];
        //[formData appendPartWithFormData:paramesters name:name];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(error);
            NSLog(@"网络请求失败！");
            NSLog(@"%@",error);
            
            if (error.code == NSURLErrorTimedOut) {
                NSLog(@"网络请求超时！");
                
            }
        }
    }];
    
}
//文件下载

+(void)downloadUrl:(NSString *)url progress:(CZPostProgress)progress success:(CZResponseSuccessBlock)success failure:(CZResponseFailureBlock)fail{
    CZNetWorkManager *manager = [CZNetWorkManager sharedInstance];
    
    NSURL *udownloadURLrl = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:udownloadURLrl];
    
    /* 下载路径 */
    //    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //    NSString *filePath = [path stringByAppendingPathComponent:url.lastPathComponent];
    
    /* 开始请求下载 */
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"总文件大小：%lld", downloadProgress.totalUnitCount);
        NSLog(@"已下载大小：%lld", downloadProgress.completedUnitCount);
        NSLog(@"进度：%lld/%lld", downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);
        NSLog(@"下载进度：%.0f％", downloadProgress.fractionCompleted * 100);
        
        
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        /* 设定下载到的位置 */
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        
        /* 设定下载到的位置 */
        //return [NSURL fileURLWithPath:filePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if (success) {
            success(filePath);
        }
        
        if (fail) {
            if (error==nil) {
                
            }else{
                fail(error);
                NSLog(@"%@",error);
            }
            
        }
    }];
    
    
    [downloadTask resume];
    
}
///* 创建网络下载对象 */
//AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//
///* 下载地址 */
//NSURL *url = [NSURL URLWithString:@"http://xxx/test.mp4"];
//NSURLRequest *request = [NSURLRequest requestWithURL:url];
//
///* 下载路径 */
//NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//NSString *filePath = [path stringByAppendingPathComponent:url.lastPathComponent];
//
///* 开始请求下载 */
//NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//
//    NSLog(@"下载进度：%.0f％", downloadProgress.fractionCompleted * 100);
//
//} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//
//    /* 设定下载到的位置 */
//    return [NSURL fileURLWithPath:filePath];
//
//} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//
//    NSLog(@"下载完成");
//
//}];
//[downloadTask resume];

+(void)QuXiaoDanGe{
    CZNetWorkManager *manager = [CZNetWorkManager sharedInstance];
    //[manager.operationQueue cancelAllOperations];
    if ([manager.tasks count] > 0) {
        NSLog(@"取消网络请求");
        [manager.tasks makeObjectsPerformSelector:@selector(cancel)];
        //NSLog(@"tasks = %@",manager.tasks);
        
    }
}
+(void)WangLuoJianTing:(id)view{
    
}
@end
